<template>
    <!-----评论列表部分------->
    <div>
        <div style="background-color: #fffef9;">
            <el-divider content-position="left"><i class="el-icon-chat-dot-square"></i>精彩评论</el-divider>
            <div class="replyList" v-for="(reply,index) in pager.records">
                <div class="replyTitle">
                    <div class="floorNumber"><i class="el-icon-location"></i>{{(pager.current-1)*pager.size+(index+1)}}楼
                    </div>
                    <div class="replyUser"><i class="el-icon-user-solid"></i>{{reply.username}}</div>
                    <div class="replyTime"><i class="el-icon-time"></i>{{reply.createTime}}</div>
                </div>
                <div class="replyContent" v-html="reply.content">

                </div>
            </div>

        </div>
        <el-pagination
                layout="prev, pager, next"
                :total="pager.total"
                :page-size="pager.size"
                @current-change="handleCurrentChange"
                :pager-count="15">
        </el-pagination>
        <!--wangEditor部分-->
        <el-divider content-position="left"><i class="el-icon-chat-line-round"></i>发表评论</el-divider>
        <div id="wangEditor">

        </div>
        <div style="text-align: center">
            <div style="display: flex;padding: 20px">
                <el-button @click="postReply" round>发表评论</el-button>
                &nbsp;
                <el-input style="width:200px;" v-model="randomCode" placeholder="请输入验证码内容" maxlength="4"></el-input>
                &nbsp;
                <el-image
                        style="width: 100px; height: 40px;cursor:pointer;"
                        :src="randomCodeImgUrl"
                        @click="changeRandomCodeImg"
                ></el-image>
            </div>
        </div>
    </div>
    <!-----评论列表部分结束------->
</template>

<script>
    import wangEditor from 'wangeditor'
    import request from "@/util/request";
    //使用jsonwebtoken生成客户端的token
    let jwt = require("jsonwebtoken");
    export default {
        name: "MyReply",
        /*
        //因为props是不可变的。
        props: {
            articleId: {
                type: String,
                default: '-1'
            }
        },*/
        data() {
            return {
                articleId: '-1',
                randomCode: '', //用户输入的验证码
                reply: {},
                //分页对象
                pager: {},
                editor: null,
                editorData: '',
                token: jwt.sign({data: new Date().getMilliseconds()}, 'www.simoniu.com', {expiresIn: 6000 * 30}), //表示客户端的一个唯一的标识符
                randomCodeImgUrl: ''
            }
        },
        mounted() {
            //console.log('当前评论的文章ID是：' + this.articleId);
            /*以下是wangEditor配置的开始*/
            const editor = new wangEditor(`#wangEditor`)
            // 配置 onchange 回调函数，将数据同步到 vue 中
            editor.config.onchange = (newHtml) => {
                this.editorData = newHtml
            }
            // 默认情况下，显示所有菜单
            editor.config.menus = [
                'head',
                'bold',
                'fontSize',
                'fontName',
                'italic',
                'indent',
                'lineHeight',
                'link',
                'list',
                'todo',
                'justify',
                'quote',
                'emoticon',
                'image',
                'table',
                'code'
            ];

            editor.config.height = 180;
            // 创建编辑器
            editor.create()
            this.editor = editor
            /*wangEditor配置的结束*/

            //初始验证码
            this.changeRandomCodeImg();
        },
        methods: {
            //初始化当前文章的评论集合,两个参数(文章ID，当前页号)
            initCurrentReplyPager(aid, currentPageNum) {
                request.get('/blog/replys/pager?aid=' + aid + '&currentPageNum=' + currentPageNum).then(resp => {
                    if (resp.data.code === 200) {
                        this.pager = resp.data.data;
                        this.articleId = aid;
                        //console.log(this.pager);
                    }
                }).catch(err => {
                    console.log(err);
                })
            },

            changeRandomCodeImg() {
                this.randomCodeImgUrl = '/commons/validateCode/servletRandomCodeImage?token=' + this.token + "&tm=" + new Date().getTime();
            },
            handleCurrentChange: function (currentPage) {
                //console.log("当前页号："+currentPage);
                this.initCurrentReplyPager(this.articleId, currentPage);
            },

            //发表评论
            async postReply() {
                //console.log("-----wangEditor的HTML内容是-----");
                //console.log(this.editor.txt.html());
                this.reply.aid = this.articleId;
                if (this.$store.state.currentLoginStatusData) {
                    //说明已经登录了
                    this.reply.username = this.$store.state.currentLoginUserInfo.username;
                    this.reply.uid = this.$store.state.currentLoginUserInfo.uid;
                } else {
                    let ipAddr = returnCitySN["cip"];
                    this.reply.username = '游客_'+ipAddr;
                    this.reply.uid = '-1';
                }
                this.reply.content = this.editor.txt.html();
                console.log("------要发表的评论对象是-----");
                console.log(this.reply);

                //1.检查验证码输入是否正确。
                //let flag = await this.checkValidateCode();
                if (await this.checkValidateCode()) {
                    //执行发表评论
                    request.post('/blog/replys/', this.reply).then(resp => {
                        if (resp.data.code === 200) {
                            //Message.success('注册成功！');
                            this.$message.success('发表评论成功！')
                            //注册成功之后自动切换到登录的tab;
                            setTimeout(this.initCurrentReplyPager(this.reply.aid, 1), 2000);
                        }
                    }).catch(err => {
                        console.log(err);
                    });
                }

            },

            //检查验证码
            async checkValidateCode() {
                let flag;
                await request.get('/commons/validateCode/auth', {
                    params: {
                        token: this.token,
                        code: this.randomCode
                    }
                }).then(resp => {
                    if (resp.data.code === 400) {
                        //Message.error('验证码验证失败！');
                        this.$message.error('验证码验证失败！')
                        flag = false;
                    } else {
                        flag = true;
                    }
                }).catch(err => {
                    console.log(err);
                });
                return flag;
            }
        }
    }
</script>

<style scoped>
    .replyTitle {
        color: #fff;
        margin: 0px;
        padding: 4px;
        border: 1px solid #B0E2FF;
        border-radius: 4px 4px 0px 0px;
        display: flex;
        background-color: #B0E2FF;
        font-size: small;
    }

    .replyList {
        padding-bottom: 0px;
        margin-bottom: 0px;
    }

    .replyContent {
        /*text-align: left;*/
        /*text-indent: 2em;*/
        font-size: small;
        padding: 5px;
    }

    .floorNumber {
        width: 10%;
    }

    .replyUser {
        width: 60%;
    }

    .replyTime {
        width: 30%;
        text-align: end;
    }
</style>